require "common/Define"
require "framework/BaseController"
require "FairyGUI"

HitTestMain = BaseController:New({mControllerName = "HitTestMain"});

function HitTestMain.Main()
	-- body
	HitTestMain:Awake();
end

function HitTestMain:Awake()
	Application.targetFrameRate = 60;
	Stage.inst.onKeyDown:Add(self.OnKeyDown, self);

	-- attack pacakge, package in resource or assetbundle
	local packageName = "UI/HitTest";
	UIPackage.AddPackage(packageName);

	local componentName = "Main";
	self.mainComponent = UIPackage.CreateObject("HitTest", componentName).asCom;
	GRoot.inst:AddChild( self.mainComponent );

	GRoot.inst:SetContentScaleFactor(1134, 640, FairyGUI.UIContentScaler.ScreenMatchMode.MatchWidthOrHeight);

	self:OnViewCreated(self.mainComponent);

end

function HitTestMain:InitView()
	local goCube = GameObject.Find("Cube");
	self.cube = goCube.transform;
	goCube:GetComponent(typeof(UnityEngine.MeshRenderer)).enabled = true;

	Stage.inst.onTouchBegin:Add(self.OnTouchBegin, self);
end

function HitTestMain:OnTouchBegin()
	print(Stage.isTouchOnUI);
	if Stage.isTouchOnUI then
		local ray = Camera.main:ScreenPointToRay(Vector2(Stage.inst.touchPosition.x, UnityEngine.Screen.height - Stage.inst.touchPosition.y));
		local hit, hitInfo = UnityEngine.Physics.Raycast(ray, nil);
		if hitInfo ~= nil then
			if (hitInfo.transform == self.cube) then
				print("Hit the cube");
			else
				print("Hit target=", hitInfo.transform.name);
			end
		end
	end
end

function HitTestMain:OnKeyDown(context)
	if (context.inputEvent.keyCode == KeyCode.Escape) then
		Application.Quit();
	end
end